import store from "@/store";
import axios from "axios";

export function exportQSZ(data) {
  return commonApi({
    method: "post",
    url: "/word/export1",
    data,
    title: "导出起诉状",
    response: {}
  });
  // return POST(baseUrl + `/word/export1`, `导出起诉状`, parmas);
}

export function exportSSCL(data) {
  // let baseUrl = store.getters.props.config.api;
  // return POST(baseUrl + `/word/export2`, `导出诉讼材料`, parmas);
  return commonApi({
    method: "post",
    url: "/word/export2",
    data,
    title: "导出起诉状",
    response: {}
  });
}

// export function getUsers() {
//   let baseUrl = store.getters.props.config.api;
//   return GET(baseUrl + `/user`, "获取用户列表");
// }

function localCommonApi(info, baseURL) {
  let { url, data, title, response } = info;
  info.method = info.method.toLowerCase();
  info.baseURL = info.base_url ? info.base_url : baseURL;
  response = response ? response : {};
  let obj = pathParse(url, data);
  info.url = obj.path;
  info.data = obj.params;
  let token = localStorage.getItem("token");
  if (!token) {
    token = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTYsInVzZXJuYW1lIjoi5YiY5LmJIiwiZXhwIjoxNjM2NzMyODIwLCJpYXQiOjE2MzE1NDg4MjB9.IpkXjZk4lhNL3BiuBEMf8-weS9UFcxaV2esEn9nb504`;
  }
  console.log(info);
  return new Promise(resolve => {
    axios({
      ...info,
      headers: {
        Authorization: "Bearer " + token
      }
    })
      .then(res => {
        if (res.status == 200) {
          let data = res.data;
          resolve(data);
        } else {
          console.error(`${title}接口调用失败`);
          resolve(response);
        }
      })
      .catch(err => {
        response.error = err ? err : true;
        console.error(`${title}接口调用失败`);
        resolve(response);
      });
  });
}

function pathParse(path = "", params = {}) {
  let infoArr = path.split(":");
  let res;
  if (infoArr.length === 1) {
    res = path;
  } else {
    res = infoArr[0];
    infoArr.forEach((item, i) => {
      if (i) {
        let key = item.replace("/", "");
        res += params[key] ? params[key] : null;
        if (i < infoArr.length - 1) {
          res += "/";
        }
        delete params[key];
      }
    });
  }

  return { path: res, params };
}

export function commonApi(info) {
  let fn;
  let baseURL = store.getters.config.api;
  if (store.getters.props.commonApi) {
    fn = store.getters.props.commonApi;
  } else {
    fn = localCommonApi;
  }

  return fn(info, baseURL);
}
